﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Prism.Modularity;
using Castle.Windsor;
using Tanmia.Basis.Security;

namespace Tanmia.Basis.Prism
{
    /// <summary>
    /// Represets a catalog created from a directory on disk. In addiotion to check for permission loading for each populated module.
    /// </summary>
    public class AuthorizedDirectoryModuleCatalog : DirectoryModuleCatalog
    {
        private readonly IWindsorContainer container;
        private readonly IAuthorizationService authorizationService;

        public AuthorizedDirectoryModuleCatalog(IWindsorContainer container, IAuthorizationService authorizationService)
        {
            this.container = container;
            this.authorizationService = authorizationService;
        }

        /// <summary>
        /// Drives the main logic of building the child domain and searching for the assemblies.
        /// </summary>
        /// <remarks>After executing the main logic of the InnerLoad method. we inject the instances of the modules in the container.</remarks>
        protected override void InnerLoad()
        {
            base.InnerLoad();
            List<ModuleInfo> deniedModules = new List<ModuleInfo>();

            foreach (ModuleInfo moduleInfo in Items)
                if (!authorizationService.IsAuthorize(string.Concat("/", moduleInfo.ModuleName, Constants.SecurityOperationLoadingModule)))
                    deniedModules.Add(moduleInfo);

            foreach (ModuleInfo moduleInfo in deniedModules)
                Items.Remove(moduleInfo);
        }

    }
}
